using System;
using System.Runtime.InteropServices;
using System.IO;

namespace rudp
{
	public enum MessageFlags : byte
	{
		Data = 1,
		ReceiptRequest = 2,
		ReceiptResponse = 3,
		ReceiptAcknowledgement = 4
	}

	[StructLayout( LayoutKind.Sequential )]
	public struct Message
	{
		public ushort 	    Id;
		public MessageFlags Flags;			
		public byte   	    Index;
		public ushort 	    DataLength;
		public byte[]       Data;

		public byte[] ToByteArray ()
		{
			byte[] data = new byte[ this.DataLength + 6 ];

			using (MemoryStream stream = new MemoryStream( data )) 
			{
				BinaryWriter writer = new BinaryWriter(stream);
				writer.Write( Id );
				writer.Write( (byte)Flags);
				writer.Write( Index );
				writer.Write( DataLength );

				if( DataLength > 0 )
					writer.Write( Data, 0, DataLength );				
			}

			return data;
		}

		public void FromByteArray (byte[] data)
		{
			using (MemoryStream stream = new MemoryStream( data )) 
			{
				BinaryReader reader = new BinaryReader (stream);

				this.Id = reader.ReadUInt16();
				this.Flags = (MessageFlags)reader.ReadByte();
				this.Index = reader.ReadByte();
				this.DataLength = reader.ReadUInt16();
				this.Data = reader.ReadBytes(this.DataLength);
			}
		}
	}
}

